package com.example.ktapplication.activity

import android.Manifest
import android.content.Context
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.location.LocationListener
import android.location.LocationManager
import android.net.Uri
import android.os.Bundle
import android.provider.MediaStore
import android.view.View
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import androidx.lifecycle.lifecycleScope
import androidx.recyclerview.widget.LinearLayoutManager
import com.bumptech.glide.Glide
import com.example.ktapplication.AppGlobals
import com.example.ktapplication.R
import com.example.ktapplication.adapter.SettingAdapter
import com.example.ktapplication.base.BaseActivity
import com.example.ktapplication.bean.SettingBean
import com.example.ktapplication.databinding.ActivitySettingBinding
import com.example.ktapplication.dialog.BottomSheetDialog
import com.example.ktapplication.enum.FunctionEnum
import com.example.ktapplication.enum.NetType
import com.example.ktapplication.utils.CleanDataUtils
import com.example.ktapplication.utils.NetworkUntil
import com.example.ktapplication.utils.SpUtils
import com.example.ktapplication.utils.ToastUtil
import com.example.ktapplication.utils.event.Event
import com.example.ktapplication.utils.event.EventBusUtil
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


class SettingActivity : BaseActivity<ActivitySettingBinding>(){


    private val REQUEST_IMAGE_CAPTURE: Int = 1211
    ///摄像头
    private val REQUEST_CAMERA_PERMISSION_CODE: Int = 101
    ///电话
    private val REQUEST_PHONE_PERMISSION_CODE: Int = 102
    ///定位
    private val REQUEST_LOCATION_PERMISSION_CODE: Int = 103
    ///相册
    private val REQUEST_PHOTO_PERMISSION_CODE: Int = 104

    private val REQUEST_FINE_LOCATIO_CODE: Int = 105
    private val REQUEST_REQUEST_PICK_IMAGE_CODE: Int = 106


    companion object {
        fun start(context: Context) {
            val intent = Intent(context, SettingActivity::class.java)
            context.startActivity(intent)
        }
    }

    val settingData by lazy {
        mutableListOf<SettingBean>().apply {
            val camera=SettingBean(FunctionEnum.CAMERA,"用于启动摄像头","摄像")
            add(camera)
            val clear=SettingBean(FunctionEnum.CLEAN,"用于清理App缓存","清理")
            add(clear)
            val photh=SettingBean(FunctionEnum.PHOTO,"用于启动相册","相册")
            add(photh)
            val phone=SettingBean(FunctionEnum.PHONE,"用于打电话","电话")
            add(phone)
            val location=SettingBean(FunctionEnum.LOCATION,"用于获取位置","定位")
            add(location)
            val message=SettingBean(FunctionEnum.MESSAGE,"用于获取通信录","通信录")
            add(message)
            val gray=SettingBean(FunctionEnum.GRAY,"用于设置为APP哀悼色","整个APP变灰")
            add(gray)

        }
    }

    interface Callback {
        fun onComplete(result: Int)
    }

    private val settingAdapter by lazy {
        SettingAdapter().apply {
            itemCallBack = object :SettingAdapter.OnItemClickListener{
                override fun onItemClick(bean: SettingBean) {
                    when(bean.type){
                        FunctionEnum.CAMERA ->{
                            val perArray = arrayOf(Manifest.permission.CAMERA)
                            requestPerssiom(perArray,REQUEST_CAMERA_PERMISSION_CODE,object : Callback {
                                override fun onComplete(result: Int) {
                                    if (result==REQUEST_CAMERA_PERMISSION_CODE){
                                        // 权限已经授予，可以直接使用摄像头
                                        val camear=Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                                        startActivityForResult(camear,REQUEST_IMAGE_CAPTURE)
                                    }
                                }
                            })
                        }
                        FunctionEnum.CLEAN -> {
                            CleanDataUtils.getInstance().clearAllCache(AppGlobals.getApplication())
                            notifyDataSetChanged()

                        }
                        FunctionEnum.PHOTO -> {
                            val perArray = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE,
                                Manifest.permission.WRITE_EXTERNAL_STORAGE)
                            requestPerssiom(perArray,REQUEST_REQUEST_PICK_IMAGE_CODE,object : Callback {
                                override fun onComplete(result: Int) {
                                    if (result==REQUEST_REQUEST_PICK_IMAGE_CODE){
                                        openAlbum()
                                    }
                                }
                            })

                        }
                        FunctionEnum.PHONE -> {
                            val perArray = arrayOf(Manifest.permission.CALL_PHONE)
                            requestPerssiom(perArray,REQUEST_PHONE_PERMISSION_CODE,object : Callback {
                                override fun onComplete(result: Int) {
                                    if (result==REQUEST_PHONE_PERMISSION_CODE){
                                        // 权限已经授予，可以直接使用电话
                                        startCallPhone()
                                    }
                                }
                            })
                        }
                        FunctionEnum.LOCATION -> {
                            location()
                        }
                        FunctionEnum.MESSAGE ->{
                            val bottomSheetDialogFragment = BottomSheetDialog(this@SettingActivity)
                            bottomSheetDialogFragment.show(supportFragmentManager,
                                "bottomSheetDialogFragment")
                        }
                        FunctionEnum.GRAY -> {
                            if (SpUtils.getInstance().getValue("GRAY",false)){
                                SpUtils.getInstance().setValue("GRAY",false)
                            }else{
                                SpUtils.getInstance().setValue("GRAY",true)
                            }
                            ToastUtil.showToast(this@SettingActivity,"设置完成请重启APP")
                        }
                    }
                }
            }
            addData(settingData)
        }
    }

    override fun getViewBind(): ActivitySettingBinding {
       return ActivitySettingBinding.inflate(layoutInflater)
    }

    override fun onDate(savedInstanceState: Bundle?) {

    }

    override fun onViewBing() {
       binding.settingTitleBar.tvTitle!!.text="设置"
       binding.settingTitleBar.imgFind!!.visibility=View.GONE
       binding.settingTitleBar.imgMenu!!.let {
            Glide.with(AppGlobals
                .getApplication())
                .load(R.mipmap.left)
                .into(it)

        }
        binding.settingTitleBar.imgMenu!!.setOnClickListener(View.OnClickListener {
            finish()
        })
        binding.rvItem.apply {
            layoutManager = LinearLayoutManager(context)
            adapter = settingAdapter
        }
        location()
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == RESULT_OK){
            if (requestCode == REQUEST_IMAGE_CAPTURE && resultCode == RESULT_OK) {
                ToastUtil.showToast(this,"在这里接收拍照完成的图片")
            }
            if (requestCode == REQUEST_REQUEST_PICK_IMAGE_CODE) {
                ToastUtil.showToast(this,"在这里接收在相册选择的图片")
            }
        }

    }

    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>,
        grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == REQUEST_CAMERA_PERMISSION_CODE) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，使用摄像头功能
                ToastUtil.showToast(this@SettingActivity,"获取到摄像头使用权限")
                val camear=Intent(MediaStore.ACTION_IMAGE_CAPTURE)
                startActivityForResult(camear,REQUEST_IMAGE_CAPTURE)
            } else {
                // 权限被拒绝，处理这种情况，例如提示用户手动开启权限或功能不可用等。
                ToastUtil.showToast(this@SettingActivity,"摄像头使用权限被拒绝")
            }
        }
        if (requestCode == REQUEST_PHONE_PERMISSION_CODE) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 权限被授予，使用摄像头功能
                ToastUtil.showToast(this@SettingActivity,"获取到电话使用权限")
                startCallPhone()
            } else {
                // 权限被拒绝，处理这种情况，例如提示用户手动开启权限或功能不可用等。
                ToastUtil.showToast(this@SettingActivity,"电话使用权限被拒绝")
            }
        }
        if (requestCode == REQUEST_FINE_LOCATIO_CODE) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                location()
            } else {
                // 权限被拒绝，处理这种情况，例如提示用户手动开启权限或功能不可用等。
                ToastUtil.showToast(this@SettingActivity,"定位权限被拒绝")
            }
        }

        if (requestCode == REQUEST_REQUEST_PICK_IMAGE_CODE) {
            if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                openAlbum()
            } else {
                // 权限被拒绝，处理这种情况，例如提示用户手动开启权限或功能不可用等。
                ToastUtil.showToast(this@SettingActivity,"访问相册权限被拒绝")
            }
        }

    }

    private fun requestPerssiom(permissions:Array<String>,requestCode:Int,callback: Callback?){
        if (ContextCompat.checkSelfPermission(this@SettingActivity,
                permissions[0]) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(this@SettingActivity, permissions,
                requestCode);
        } else {
            // 权限已经授予
            callback?.onComplete(requestCode)
        }
    }

    private fun startCallPhone() {
        val callIntent = Intent(Intent.ACTION_CALL)
        callIntent.setData(Uri.parse("tel:$10086"))
        startActivity(callIntent)
    }

    // 打开相册方法
    private fun openAlbum() {
        // 创建一个 Intent，用于打开设备的相册，选择图片
        val galleryIntent = Intent(Intent.ACTION_PICK,
            android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
        // 启动相册 Activity 并期望返回结果
        startActivityForResult(galleryIntent, REQUEST_REQUEST_PICK_IMAGE_CODE);
    }

    fun location(){
        val type=NetworkUntil.getInstance().getNetworkType(this@SettingActivity)
        when(type){
            NetType.MOBILE ->{
                wifiLocation()
            }
            NetType.WIFI ->{
                wifiLocation()
            }
            NetType.NONE -> {
                ToastUtil.showToast(this@SettingActivity,"无法获取网络类型")
            }
        }
    }
    fun wifiLocation(){
        // 获取系统的Location Manager
        val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager
       // 检查是否有网络定位的权限
        if (ActivityCompat.checkSelfPermission(this@SettingActivity,
                Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            // 请求网络定位信息
            locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER,
                0,
                0f,
                object : LocationListener {
                    override fun onLocationChanged(location: Location) {
                        // 在这里处理获取到的位置信息
                        val latitude: Double = location.getLatitude()
                        val longitude: Double = location.getLongitude()
                        val speed = location.speed // m/s
                        displayLocation(latitude, longitude, speed)
                        lifecycleScope.launch(Dispatchers.Main){
                            settingAdapter.setLocationContent(latitude.toString(),longitude.toString())
                        }
                    }
                })
        }else{
            val perArray = arrayOf(Manifest.permission.ACCESS_FINE_LOCATION)
            requestPerssiom(perArray,REQUEST_FINE_LOCATIO_CODE,null)
        }
    }
    fun displayLocation(latitude:Double,longitude:Double, speed:Float) {
        // 将位置信息和速度显示在界面上
    }
}